package internet.client;

import com.example.internet.Request;
import com.example.internet.Response;
import internet.utils.BytesUtils;

import java.io.IOException;
import java.net.*;

public class ContactsClient {
    private static final SocketAddress ADDRESS = new InetSocketAddress("localhost", 8888);

    public static void main(String[] args) throws IOException {
        // 创建客户端 DatagramSocket
        DatagramSocket socket = new DatagramSocket();
        // 生成发送数据
        Request request = Request.newBuilder()
                .setName("张三")
                .setAge(18)
                .setName("12345678")
                .build();
        byte[] requestData = request.toByteArray();
        DatagramPacket packet = new DatagramPacket(requestData, requestData.length, ADDRESS);
        // 发送数据给服务器
        socket.send(packet);
        System.out.println("客户端发送数据成功");
        // 接搜服务器响应
        byte[] responseData = new byte[1024];
        DatagramPacket responsePackage = new DatagramPacket(responseData, responseData.length);
        socket.receive(responsePackage);
        int length = BytesUtils.getValidLength(responseData);
        byte[] responseBytes = BytesUtils.subByte(responseData, 0, length);
        Response response = Response.parseFrom(responseBytes);
        System.out.println("接收到服务器响应: " + response.toString());
    }
}
